package com.gitee.maskit.data.redis;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.net.UnknownHostException;

public class RedisTemplates {
    private static class ExtendedRedisAutoConfiguration extends RedisAutoConfiguration {
        static JedisConnectionFactory jedisConnectionFactory(
            RedisProperties properties,
            ObjectProvider<RedisSentinelConfiguration> redisSentinelConfigurationObjectProvider,
            ObjectProvider<RedisClusterConfiguration> redisClusterConfigurationObjectProvider
        ) throws UnknownHostException {
            return new RedisAutoConfiguration.RedisConnectionConfiguration(properties,
                redisSentinelConfigurationObjectProvider, redisClusterConfigurationObjectProvider)
                .redisConnectionFactory();
        }
    }

    public JedisConnectionFactory jedisConnectionFactory(
        RedisProperties properties,
        ObjectProvider<RedisSentinelConfiguration> redisSentinelConfigurationObjectProvider,
        ObjectProvider<RedisClusterConfiguration> redisClusterConfigurationObjectProvider
    ) throws UnknownHostException {
        return ExtendedRedisAutoConfiguration.jedisConnectionFactory(
            properties, redisSentinelConfigurationObjectProvider,
            redisClusterConfigurationObjectProvider);
    }

    public <K, V> RedisTemplate<K, V> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<K, V> template = new RedisTemplate<K, V>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}
